import argparse
from pynput import mouse, keyboard
import time
from PyQt5.QtCore import QRect, QPoint
from PyQt5.QtCore import QObject,QThread
from PyQt5.QtWidgets import QFileDialog
import threading

# time , mv , x , y
# time , mw , dx , dy , x , y
# time , mc , keys , p(1)/r(0) , x , y
# time , kc , keys , p(1)/r(0)

class Recorder:
    operation_records = []
    start_time = 0
    filter_move = False
    filter_mid = False
    filter_left = False
    filter_right = False
    filter_key = False
    filter_rect = QRect(0,0,0,0)   #过滤录制区域，如控制页面区域
    stopRunning = False         # 此变量用于控制线程的运行
    current_keys = set()    # 定义一个变量来追踪键盘状态

    def __init__(self):
        id = threading.get_ident()
        print(f"初始化录制模块...,threadId{id}")

        self.mouse_listener = mouse.Listener(on_move=self.mouse_move, on_click=self.mouse_click, on_scroll=self.mouse_wheel)
        self.keyBoard_listener = keyboard.Listener(on_press=self.key_press, on_release=self.key_release)

    def startRecord(self) :
        self.start_time = time.time()
        self.mouse_listener.start()
        self.keyBoard_listener.start()
        print(f"启动录制,时间:{self.start_time}")

    def stopRecord(self) :
        self.mouse_listener.stop()
        self.keyBoard_listener.stop()
        print(f"已停止录制")

    def export(self, fileName) :
        with open(fileName, "w") as f:
            for record in self.operation_records:
                f.write(record + "\n")
        print(f"操作记录已保存:{fileName}")

    def setFilterRect(self,x,y,width,height) : 
        self.filter_rect = QRect(x,y,width,height)
        
    def setFilterOpt(self,move,mid,left,right,key) :
        self.filter_move = move
        self.filter_mid = mid
        self.filter_left = left
        self.filter_right = right
        self.filter_key = key
        
    def mouse_move(self,x,y) : 
        if self.filter_move or self.filter_rect.contains(QPoint(x,y)) :
            return 
        
        optInfo = f"{time.time() - self.start_time:.2f}, mv, {int(x)}, {int(y)}"
        self.operation_records.append(optInfo)
        print(optInfo)

    # 定义鼠标按下事件的回调函数
    def mouse_click(self,x, y, button, pressed):
        if self.filter_rect.contains(QPoint(x,y)) :
            return 
        
        if button == mouse.Button.middle :
            if self.filter_mid :
                return 
            if pressed:
                optInfo = f"{time.time() - self.start_time:.2f}, mc, 0 , 1 , {int(x)}, {int(y)}"
            else :
                optInfo = f"{time.time() - self.start_time:.2f}, mc, 0 , 0 , {int(x)}, {int(y)}"
            self.operation_records.append(optInfo)
            print(optInfo)

        if button == mouse.Button.left :
            if self.filter_left :
                return 
            if pressed:
                optInfo = f"{time.time() - self.start_time:.2f}, mc, 1 , 1 , {int(x)}, {int(y)}"
            else :
                optInfo = f"{time.time() - self.start_time:.2f}, mc, 1 , 0 , {int(x)}, {int(y)}"
            self.operation_records.append(optInfo)
            print(optInfo)

        if button == mouse.Button.right :
            if self.filter_right :
                return 
            if pressed:
                optInfo = f"{time.time() - self.start_time:.2f}, mc, 2 , 1 , {int(x)}, {int(y)}"
            else :
                optInfo = f"{time.time() - self.start_time:.2f}, mc, 2 , 0 , {int(x)}, {int(y)}"
            self.operation_records.append(optInfo)
            print(optInfo)

    def mouse_wheel(self,x, y, dx:float, dy:float):
        if self.filter_mid or self.filter_rect.contains(QPoint(x,y)) :
            return 
        optInfo = f"{time.time() - self.start_time:.2f}, mw, {dx} , {dy} , {int(x)}, {int(y)}"
        self.operation_records.append(optInfo)
        print(optInfo)

    def key_press(self,key) : 
        self.current_keys.add(key)
        if self.filter_key :
            return 
        optInfo =  f"{time.time() - self.start_time:.2f}, kc, {key} , 1"
        self.operation_records.append(optInfo)
        print(optInfo)

    def key_release(self,key) : 
        self.current_keys.remove(key)
        if self.filter_key :
            return 
        optInfo =  f"{time.time() - self.start_time:.2f}, kc, {key} , 0"
        self.operation_records.append(optInfo)
        print(optInfo)

    def isQuit(self) :
        if keyboard.Key.left in self.current_keys and keyboard.Key.right in self.current_keys and keyboard.Key.down in self.current_keys:
            self.operation_records[-3:]
            return True
        else :
            return False      

recorder = Recorder()
recorder.startRecord()

while not recorder.isQuit() :
    time.sleep(0.01)

recorder.stopRecord()

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()  # 隐藏根窗口

file_path = filedialog.asksaveasfilename(defaultextension=".txt",
                                          filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
if file_path:
    print("Selected file path:", file_path)
    recorder.export(file_path)
else:
    print("No file selected.")


